package com.example.workflow.service.impl;

import com.example.workflow.dto.ProcessStartDTO;
import com.example.workflow.dto.TaskCompleteDTO;
import com.example.workflow.service.ProcessOpenApiService;
import com.example.workflow.vo.ProcessDefinitionVO;
import com.example.workflow.vo.ProcessInstanceVO;
import com.example.workflow.vo.TaskVO;

import ch.qos.logback.core.joran.util.beans.BeanUtil;

import com.example.workflow.vo.ProcessInstanceDetailVO;
import com.example.workflow.vo.TaskHistoryVO;
import lombok.RequiredArgsConstructor;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
import org.flowable.engine.*;
import com.example.workflow.mapper.SysProcessMapper;
import com.example.workflow.entity.SysProcess;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.engine.task.Comment;
import org.flowable.task.api.history.HistoricTaskInstance;
@Service
@RequiredArgsConstructor
public class ProcessOpenApiServiceImpl implements ProcessOpenApiService {
    private final RuntimeService runtimeService;
    private final TaskService taskService;
    private final HistoryService historyService;
    private final RepositoryService repositoryService;
    private final SysProcessMapper processMapper;

    @Override
    public List<ProcessDefinitionVO> listProcesses(Long systemId) {
        List<SysProcess> processes = processMapper.selectBySystemId(systemId);
        return processes.stream()
                .map(process -> {
                    ProcessDefinitionVO vo = new ProcessDefinitionVO();
                    vo.setId(process.getId());
                    vo.setProcessKey(process.getProcessKey());
                    vo.setProcessName(process.getProcessName());
                    vo.setProcessDefinitionId(process.getProcessDefinitionId());
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String startProcess(ProcessStartDTO startDTO) {
        // 验证流程是否存在
        SysProcess process = processMapper.selectBySystemIdAndKey(
                startDTO.getSystemId(), startDTO.getProcessKey());
        if (process == null) {
            throw new RuntimeException("流程不存在");
        }

        // 启动流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
                startDTO.getProcessKey(),
                startDTO.getBusinessKey(),
                startDTO.getVariables()
        );

        return processInstance.getId();
    }

    @Override
    public List<ProcessInstanceVO> listProcessInstances(Long systemId) {
        List<SysProcess> processes = processMapper.selectBySystemId(systemId);
        List<String> processDefinitionIds = processes.stream()
                .map(SysProcess::getDeploymentId)
                .collect(Collectors.toList());

        return runtimeService.createProcessInstanceQuery()
                .deploymentIdIn(processDefinitionIds)
                .list()
                .stream()
                .map(process -> {
                    ProcessInstanceVO vo = new ProcessInstanceVO();
                    BeanUtils.copyProperties(process, vo);
                    vo.setId(process.getId());
                    vo.setProcessKey(process.getProcessDefinitionKey());
                    vo.setProcessName(process.getProcessDefinitionName());
                    vo.setProcessDefinitionId(process.getProcessDefinitionId());
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void completeTask(TaskCompleteDTO taskDTO) {
        Task task = taskService.createTaskQuery()
                .taskId(taskDTO.getTaskId())
                .taskCandidateOrAssigned(taskDTO.getRoleId())
                .singleResult();

        if (task == null) {
            throw new RuntimeException("任务不存在或无权限处理");
        }

        // 添加处理意见
        taskService.addComment(
                taskDTO.getTaskId(),
                task.getProcessInstanceId(),
                taskDTO.getAction(),
                taskDTO.getComment()
        );

        // 完成任务
        taskService.complete(taskDTO.getTaskId(), taskDTO.getVariables());
    }

    @Override
    public List<TaskVO> listRoleTasks(String roleId) {
        return taskService.createTaskQuery()
                .taskCandidateOrAssigned(roleId)
                .list()
                .stream()
                .map(process -> {
                    TaskVO vo = new TaskVO();
                    BeanUtils.copyProperties(process, vo);
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public ProcessInstanceDetailVO getProcessInstanceDetail(String processInstanceId) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        ProcessInstanceDetailVO detail = new ProcessInstanceDetailVO();
        if (processInstance != null) {
            // 设置基本信息
            detail.setProcessInstanceId(processInstance.getId());
            detail.setProcessDefinitionName(processInstance.getProcessDefinitionName());
            detail.setBusinessKey(processInstance.getBusinessKey());
            detail.setStartTime(processInstance.getStartTime());
            detail.setCurrentActivity(processInstance.getActivityId());
            detail.setStatus("运行中");
        } else {
            // 查询历史数据
            HistoricProcessInstance historicInstance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            if (historicInstance != null) {
                detail.setProcessInstanceId(historicInstance.getId());
                detail.setProcessDefinitionName(historicInstance.getProcessDefinitionName());
                detail.setBusinessKey(historicInstance.getBusinessKey());
                detail.setStartTime(historicInstance.getStartTime());
                detail.setStatus(historicInstance.getEndTime() != null ? "已完成" : "已终止");
            }
        }

        // 获取历史任务记录
        List<TaskHistoryVO> history = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricTaskInstanceStartTime().asc()
                .list()
                .stream()
                .map(this::convertToTaskHistoryVO)
                .collect(Collectors.toList());
        
        detail.setHistory(history);
        return detail;
    }

    private  TaskHistoryVO convertToTaskHistoryVO(HistoricTaskInstance historicTask) {
        TaskHistoryVO vo = new TaskHistoryVO();
        vo.setTaskId(historicTask.getId());
        vo.setTaskName(historicTask.getName());
        vo.setAssignee(historicTask.getAssignee());
        vo.setStartTime(historicTask.getStartTime());
        vo.setEndTime(historicTask.getEndTime());
        vo.setDurationInMillis(historicTask.getDurationInMillis());
        
        // 获取任务的处理意见
        if (historicTask.getEndTime() != null) {
            List<Comment> comments = taskService.getTaskComments(historicTask.getId());
            if (!comments.isEmpty()) {
                Comment lastComment = comments.get(comments.size() - 1);
                vo.setAction(lastComment.getType());
                vo.setComment(lastComment.getFullMessage());
            }
        }
        
        return vo;
    }

    // 转换方法...（省略具体实现）
} 